package com.zzyl.nursing.service.impl;

import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.ContractNumberGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInConfigDto;
import com.zzyl.serve.dto.CheckInContractDto;
import com.zzyl.serve.dto.CheckInElderDto;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 申请入住
     *
     * @param dto
     */
    @Transactional
    @Override
    public void addLy(CheckInApplyDto dto) {
        //1.判断老人是否入住
        //根据身份证查找老人信息是否存在
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
//                //查询入住状态
//                .in(Elder::getStatus, List.of(2, 3, 4));
        Elder elderin = elderMapper.selectOne(elderQueryWrapper);
        if (elderin != null && elderin.getStatus() >= 1 && elderin.getStatus() <= 4) {
            throw new SecurityException("该老人已入住");
        }
        //2.更改床位状态为已入住
        //2.1从表中根据床位id查询
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        if (bed.getBedStatus() == 1) {
            throw new SecurityException("该床位已入住");
        }
        //2.2如果床位没有被占用
        LambdaUpdateWrapper<Bed> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Bed::getBedStatus, 1);
        //2.3.在多线程的情况下 ,多个老人来抢这个床位, 根据床位主键id可以把床位的状态利用行锁锁住,更新成功返回1,否则返回0,
        lambdaUpdateWrapper.eq(Bed::getBedStatus, 0);
        lambdaUpdateWrapper.eq(Bed::getId, bed.getId());
        int update = bedMapper.update(null, lambdaUpdateWrapper);
        if (update == 0) {
            throw new ServiceException("该床位已有人了");
        }
        //
        //3.新增老人或更新
        Elder elder = insertOrUpdate(elderin, bed, dto.getCheckInElderDto());

        //4.新增签约办理
        insertContract(elder, dto);

        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, bed, dto);

        //6.新增入住配置
        insertCheckInConfig(checkIn.getId(), dto);

    }

    /**
     * 新增入住配置
     *
     * @param id
     * @param dto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = BeanUtil.toBeanIgnoreError(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param dto
     * @return
     */
    private CheckIn insertCheckIn(Elder elder, Bed bed, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setElderId(elder.getId());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        save(checkIn);
        return checkIn;

    }

    /**
     * 新增签约办理
     *
     * @param elder
     * @param dto
     */
    private void insertContract(Elder elder, CheckInApplyDto dto) {
        //生成合同编码
        String contractNo = "HT" + ContractNumberGenerator.generateContractNumber();
        //把dto转换为实体类的对象并忽略错误
        Contract contract = BeanUtil.toBeanIgnoreError(dto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        contract.setStatus(0);  //审核完
        contract.setSignDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contractMapper.insertContract(contract);

    }

    /**
     * 新增老人或更新
     *
     * @param elderin
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Elder elderin, Bed bed, CheckInElderDto checkInElderDto) {
        //创建并拷贝属性值并去除不要的属性
        Elder elder = BeanUtil.toBeanIgnoreError(checkInElderDto, Elder.class);
        //补充没有的属性值
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);


        if (elderin != null) {
            //更新
            elder.setId(elderin.getId());
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;


    }
}
